import java.util.Arrays;

/**
 * 16. 最接近的三数之和
 */
public class No16 {
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);

        boolean isFirst = true;
        int resClose = 0;
        int resNum = 0;
        for (int i = 0; i < n - 2; i++) {
            int j = i + 1, k = n - 1;

            while (j < k) {
                int temp = nums[i] + nums[j] + nums[k];
                int abs = Math.abs(target - temp);
                if (isFirst || abs < resClose) {
                    isFirst = false;
                    resClose = abs;
                    resNum = temp;
                }
                if (nums[i] + nums[j] + nums[k] == target) {
                    break;
                } else if (nums[j] + nums[k] < target - nums[i]) {
                    j++;
                } else if (nums[j] + nums[k] > target - nums[i]) {
                    k--;
                }
            }
        }
        return resNum;
    }
}
